package com.wmlive.hhvideo.heihei.personal.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wmlive.hhvideo.common.base.DcBaseFragment;
import com.wmlive.hhvideo.heihei.beans.main.MultiTypeVideoBean;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoItem;
import com.wmlive.hhvideo.heihei.beans.personal.ListLikeResponse;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.fragment.RecommendFragmentNew;
import com.wmlive.hhvideo.heihei.mainhome.activity.VideoListActivity;
import com.wmlive.hhvideo.heihei.personal.RecyclerScrollListener;
import com.wmlive.hhvideo.heihei.personal.adapter.PersonalLoveAdapter;
import com.wmlive.hhvideo.heihei.personal.presenter.PersonalLovePresenter;
import com.wmlive.hhvideo.heihei.personal.util.SpaceItemDecoration;
import com.wmlive.hhvideo.heihei.personal.view.IPersonalLoveView;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.widget.refreshrecycler.OnRecyclerItemClickListener;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;

/**
 * Created by XueFei on 2017/6/2.
 * <p>
 * 个人主页--他人主页--喜欢的作品
 */

public class PersonalLoveFragment extends DcBaseFragment implements SwipeRefreshLayout.OnRefreshListener, RefreshRecyclerView.OnLoadMoreListener, IPersonalLoveView, OnRecyclerItemClickListener, RecyclerScrollListener {

    @BindView(R.id.rv_list)
    RefreshRecyclerView rcvList;
    @BindView(R.id.tvEmptyMessage)
    TextView tvEmptyMessage;

    private PersonalLoveAdapter personalLoveAdapter;
    private PersonalLovePresenter personalLovePresenter;
    private IPersonalLoveView iPersonalLoveView;

    private long user_id;
    private int offset = 0;
    private boolean isLoadMore = false;

    private RecyclerScrollListener mScrollListener;
    private int mScrollY = 0;


    public static PersonalLoveFragment newInstance() {
        PersonalLoveFragment fragment = new PersonalLoveFragment();
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_personal_product_love;
    }

    @Override
    protected void initData() {
        super.initData();

        iPersonalLoveView = this;
        personalLovePresenter = new PersonalLovePresenter(iPersonalLoveView);
        addPresenter(personalLovePresenter);

        Bundle bundle = getArguments();
        user_id = bundle.getLong("user_id", 0);
        int headHeight = bundle.getInt("headHeight", 0);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
        rcvList.setLayoutManager(gridLayoutManager);
        personalLoveAdapter = new PersonalLoveAdapter(new ArrayList<ShortVideoItem>(), rcvList);
        rcvList.addItemDecoration(new SpaceItemDecoration(8, true));
        rcvList.setAdapter(personalLoveAdapter);
        rcvList.setOnRefreshListener(this);
        rcvList.setOnLoadMoreListener(this);
        rcvList.autoRefresh();

        AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, headHeight);
        View view = new LinearLayout(getActivity());
        view.setLayoutParams(params);
        rcvList.setHeader(view);

        personalLoveAdapter.setOnRecyclerItemClickListener(this);

        if (AccountUtil.getUserId() == user_id) {
            tvEmptyMessage.setText(R.string.user_no_like_opus);
        } else {
            tvEmptyMessage.setText(R.string.user_other_no_like_opus);
        }
        personalLoveAdapter.setShowEmptyView(false);

        rcvList.getRecycleView().addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(getActivity()).resumeRequests();
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    Glide.with(getActivity()).pauseRequests();
                } else if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    Glide.with(getActivity()).pauseRequests();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (personalLoveAdapter.getItemCount() > 3) {
                    mScrollY += dy;
                    if (mScrollListener != null) {
                        mScrollListener.Scrolled(mScrollY, 1);
                    }
                }
            }
        });
    }

    @Override
    protected void onVisible() {
        super.onVisible();

        if (null != rcvList) {
            onRefresh();
        }
    }

    @Override
    public void handlePersonalLoveListSucceed(ListLikeResponse response) {
        List<ShortVideoItem> opusList = response.getUser_like_list();

        personalLoveAdapter.addData(!isLoadMore, opusList);

        if (opusList.size() > 0) {
            tvEmptyMessage.setVisibility(View.GONE);
        } else {
            tvEmptyMessage.setVisibility(View.VISIBLE);

            ViewTreeObserver vto = rcvList.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    rcvList.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    int rcvListHeight = rcvList.getHeight();
                    int headerHeight = rcvList.getHeader().getHeight();

                    tvEmptyMessage.getLayoutParams().height = rcvListHeight - headerHeight;
                }
            });
        }

        offset = response.getOffset();
    }

    @Override
    public void handlePersonalLoveListFailure(String error_msg) {
        ToastUtil.showToast(error_msg);
        personalLoveAdapter.showError(!isLoadMore);
    }

    @Override
    public void onRefresh() {
        reCreateView();
        reCreatePressenter();
        personalLovePresenter.setView(iPersonalLoveView);
        isLoadMore = false;
        offset = 0;
        personalLovePresenter.getPersonaLovelList(user_id, offset);
    }

    @Override
    public void onLoadMore() {
        personalLovePresenter.setView(iPersonalLoveView);
        isLoadMore = true;
        personalLovePresenter.getPersonaLovelList(user_id, offset);
    }

    @Override
    protected void onSingleClick(View v) {

    }

    @Override
    public void onRecyclerItemClick(int dataPosition, View view, Object data) {
        VideoListActivity.startActivity(getActivity(),
                RecommendFragmentNew.TYPE_LIKE,
                MultiTypeVideoBean.createUserParma(user_id, dataPosition, personalLoveAdapter.getDataContainer()));
    }

    @Override
    public void Scrolled(int distance, int pagePosition) {

    }

    @Override
    public void adjustScroll(final int scrollHeight, int headerHeight) {
        if (rcvList == null) {
            return;
        }
        mScrollY = headerHeight - scrollHeight;
        rcvList.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (rcvList.getChildCount() > 0) {
                    rcvList.getViewTreeObserver().removeOnPreDrawListener(this);
                    ((GridLayoutManager) rcvList.getLayoutManager()).scrollToPositionWithOffset(0, -mScrollY);
                    return true;
                }
                return false;
            }
        });
    }

    public void getmScrollListener(RecyclerScrollListener scrollListener) {
        mScrollListener = scrollListener;
    }

    private void reCreateView() {
        if (null == iPersonalLoveView) {
            iPersonalLoveView = new IPersonalLoveView() {

                @Override
                public void handlePersonalLoveListSucceed(ListLikeResponse response) {
                    PersonalLoveFragment.this.handlePersonalLoveListSucceed(response);
                }

                @Override
                public void handlePersonalLoveListFailure(String error_msg) {
                    PersonalLoveFragment.this.handlePersonalLoveListFailure(error_msg);
                }

                @Override
                public void onRequestDataError(int requestCode, String message) {
                    PersonalLoveFragment.super.onRequestDataError(requestCode, message);
                }

                @Override
                public void handleNetError() {
                    PersonalLoveFragment.super.handleNetError();
                }
            };
        }
    }

    private void reCreatePressenter() {
        if (null == personalLovePresenter) {
            personalLovePresenter = new PersonalLovePresenter(iPersonalLoveView);
            addPresenter(personalLovePresenter);
        }
    }

    /**
     * 账号被踢后，fragment没有销毁 导致Uuser_id为之前帐号的
     *
     * @param user_id
     */
    public void setUserId(long user_id) {
        this.user_id = user_id;
    }
}